package com.share.ocr;

import com.baidu.aip.util.Base64Util;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * author:caifan
 * date:2019/10/7
 */
public class CaptureScreen_01 {
    private JFrame jFrame = null;
    JLabel imgLabel = null;

    public void init(CaptureScreen_01 captureScreen) {
        jFrame = new JFrame("HelloOCR");
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Point point = new Point();
        point.setLocation(screenSize.width * 4 / 5, screenSize.height * 3 / 5);
        jFrame.setLocation(point);
        jFrame.setSize(screenSize.width / 5, screenSize.height / 4);


        JMenuBar menuBar = new JMenuBar();

        imgLabel = new JLabel();
        imgLabel.setBackground(Color.WHITE);

        JTextArea textArea = new JTextArea();
        JTextPane textPane = new JTextPane();
        textPane.add(textArea);
        JScrollPane textScrollPane = new JScrollPane();
        textScrollPane.add(textPane);

        JPanel buttonPanel = new JPanel();
        JButton buttonCapture = new JButton("截屏");
        JButton buttonFile = new JButton("读取文件");
        JButton buttonOCR = new JButton("OCR");

        buttonCapture.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ScreenShotWindow ssw = new ScreenShotWindow(captureScreen);
                                ssw.setVisible(true);
                            } catch (AWTException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e1) {
                    JOptionPane.showConfirmDialog(null, "出现意外错误！", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        buttonOCR.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ImageIcon icon = (ImageIcon)imgLabel.getIcon();
                BufferedImage image = new BufferedImage(icon
                .getImage().getWidth(null), icon.getImage().getHeight(null), BufferedImage.TYPE_INT_RGB);
                ByteArrayOutputStream imageStream = new ByteArrayOutputStream();

                try {
                    ImageIO.write(image, "png", imageStream);
                    String textOCR = BaiduOCR.textOCR(Base64.getDecoder().decode(imageStream.toByteArray()));
                    textArea.setText(textOCR);
                    System.out.println(textArea.getText());
                } catch(Exception e1) {
                    e1.printStackTrace();
                }
            }
        });

        buttonPanel.add(buttonCapture);
        buttonPanel.add(buttonFile);
        buttonPanel.add(buttonOCR);

        jFrame.setLayout(new BorderLayout(10,5));
        jFrame.add(menuBar, BorderLayout.NORTH);
        jFrame.add(imgLabel, BorderLayout.CENTER);
        jFrame.add(textScrollPane, BorderLayout.EAST);
        jFrame.add(buttonPanel, BorderLayout.SOUTH);

        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        jFrame.setLocationRelativeTo(null);
        jFrame.setVisible(true);


    }

    public static void main(String[] args) {
        CaptureScreen_01 captureScreen = new CaptureScreen_01();
        captureScreen.init(captureScreen);
        /*EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    ScreenShotWindow ssw = new ScreenShotWindow();
                    ssw.setVisible(true);
                } catch (AWTException e) {
                    e.printStackTrace();
                }
            }
        });*/
    }
}

/*
 * 截图窗口
 */
class ScreenShotWindow extends JWindow {
    private int orgx, orgy, endx, endy;
    private BufferedImage image = null;
    private BufferedImage tempImage = null;
    private BufferedImage saveImage = null;

    private ToolsWindow tools = null;

    private CaptureScreen_01 captureScreen;

    public ScreenShotWindow(CaptureScreen_01 captureScreen) throws AWTException {
        this.captureScreen = captureScreen;
//获取屏幕尺寸
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setBounds(0, 0, d.width, d.height);

//截取屏幕
        Robot robot = new Robot();
        image = robot.createScreenCapture(new Rectangle(0, 0, d.width, d.height));

        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
//鼠标松开时记录结束点坐标，并隐藏操作窗口
                orgx = e.getX();
                orgy = e.getY();

                if (tools != null) {
                    tools.setVisible(false);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
//鼠标松开时，显示操作窗口
                if (tools == null) {
                    tools = new ToolsWindow(ScreenShotWindow.this, e.getX(), e.getY());
                } else {
                    tools.setLocation(e.getX(), e.getY());
                }
                tools.setVisible(true);
                tools.toFront();
            }
        });

        this.addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseDragged(MouseEvent e) {
//鼠标拖动时，记录坐标并重绘窗口
                endx = e.getX();
                endy = e.getY();

//临时图像，用于缓冲屏幕区域放置屏幕闪烁
                Image tempImage2 = createImage(ScreenShotWindow.this.getWidth(), ScreenShotWindow.this.getHeight());
                Graphics g = tempImage2.getGraphics();
                g.drawImage(tempImage, 0, 0, null);
                int x = Math.min(orgx, endx);
                int y = Math.min(orgy, endy);
                int width = Math.abs(endx - orgx) + 1;
                int height = Math.abs(endy - orgy) + 1;
// 加上1防止width或height0
                g.setColor(Color.BLUE);
                g.drawRect(x - 1, y - 1, width + 1, height + 1);
//减1加1都了防止图片矩形框覆盖掉
                saveImage = image.getSubimage(x, y, width, height);
                g.drawImage(saveImage, x, y, null);

                ScreenShotWindow.this.getGraphics().drawImage(tempImage2, 0, 0, ScreenShotWindow.this);
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        RescaleOp ro = new RescaleOp(0.8f, 0, null);
        tempImage = ro.filter(image, null);
        g.drawImage(tempImage, 0, 0, this);
    }

    //保存图像到文件
    public void saveImage() throws IOException {
        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle("保存");

//文件过滤器，用户过滤可选择文件
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg");
        jfc.setFileFilter(filter);

//初始化一个默认文件（此文件会生成到桌面上）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
        String fileName = sdf.format(new Date());
        File filePath = FileSystemView.getFileSystemView().getHomeDirectory();
        File defaultFile = new File(filePath + File.separator + fileName + ".jpg");
        jfc.setSelectedFile(defaultFile);

        int flag = jfc.showSaveDialog(this);
        if (flag == JFileChooser.APPROVE_OPTION) {
            File file = jfc.getSelectedFile();
            String path = file.getPath();
//检查文件后缀，放置用户忘记输入后缀或者输入不正确的后缀
            if (!(path.endsWith(".jpg") || path.endsWith(".JPG"))) {
                path += ".jpg";
            }
//写入文件
            ImageIO.write(saveImage, "jpg", new File(path));
//            System.exit(0);
        }
    }

    public void copyImage() {
        captureScreen.imgLabel.setIcon(new ImageIcon(saveImage));
        this.dispose();
    }
}

/*
 * 操作窗口
 */
class ToolsWindow extends JWindow {
    private ScreenShotWindow parent;

    public ToolsWindow(ScreenShotWindow parent, int x, int y) {
        this.parent = parent;
        this.init();
        this.setLocation(x, y);
        this.pack();
        this.setVisible(true);
    }

    private void init() {

        this.setLayout(new BorderLayout());
        JToolBar toolBar = new JToolBar("Java 截图");

//保存按钮
        JButton saveButton = new JButton(new ImageIcon("images/save.gif"));
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    parent.saveImage();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        toolBar.add(saveButton);

        JButton copyButton = new JButton("copy");
        copyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    parent.copyImage();

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
        toolBar.add(copyButton);

//关闭按钮
        JButton closeButton = new JButton(new ImageIcon("images/close.gif"));
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        toolBar.add(closeButton);

        this.add(toolBar, BorderLayout.NORTH);
    }
}
